package org.agilelang.db.toagile;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.awt.event.ActionEvent;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.agilelang.object.Model;
import org.agilelang.object.attributes.Attribute;
import org.agilelang.object.attributes.Reference;

public class DlgSelectTables extends javax.swing.JDialog {

    List<Model> models;
    boolean status = false;
    DefaultTableModel tbm = new DefaultTableModel(
            new Object[][]{},
            new String[]{
                "Name Table", "Name Model(singularize)", "Description", "Create"
            }) {
        Class[] types = new Class[]{
            java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
        };

        @Override
        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            if (column == 0 || column == 1) {
                return false;
            } else {
                return true;
            }
        }
    };
    DefaultTableModel tbm_column = new DefaultTableModel(
            new Object[][]{},
            new String[]{
                "Name", "Type", "Size", "Nullable", "Description"
            }) {
        Class[] types = new Class[]{
            java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Object.class,};

        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }
    };
    DefaultTableModel tbm_keys = new DefaultTableModel(
            new Object[][]{},
            new String[]{
                "Name Reference", "Foreign Key", "Class Reference", "Attribute Reference", "Field Reference", "Description"
            }) {
        Class[] types = new Class[]{
            java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
        };

        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }
    };
    int postable = -1;
    JComboBox comboBox = new JComboBox();

    public DlgSelectTables(java.awt.Frame parent, boolean modal, List<Model> models1) {
        super(parent, modal);
        this.models = models1;
        initComponents();
        tblTable.setModel(tbm);
        tblColumn.setModel(tbm_column);
        tblKey.setModel(tbm_keys);

        tblTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblTable.getColumnModel().getColumn(0).setPreferredWidth(150);
        tblTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        tblTable.getColumnModel().getColumn(2).setPreferredWidth(430);
        tblTable.getColumnModel().getColumn(3).setPreferredWidth(50);//780

        tblColumn.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblColumn.getColumnModel().getColumn(0).setPreferredWidth(150);
        tblColumn.getColumnModel().getColumn(1).setPreferredWidth(150);
        tblColumn.getColumnModel().getColumn(2).setPreferredWidth(40);
        tblColumn.getColumnModel().getColumn(3).setPreferredWidth(60);
        tblColumn.getColumnModel().getColumn(4).setPreferredWidth(388);
        //tblColumn.getColumnModel().getColumn(5).setPreferredWidth(328);

        tblKey.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblKey.getColumnModel().getColumn(0).setPreferredWidth(110);
        tblKey.getColumnModel().getColumn(1).setPreferredWidth(90);
        tblKey.getColumnModel().getColumn(2).setPreferredWidth(110);
        tblKey.getColumnModel().getColumn(3).setPreferredWidth(120);
        tblKey.getColumnModel().getColumn(4).setPreferredWidth(110);
        tblKey.getColumnModel().getColumn(5).setPreferredWidth(240);

        int t = models.size();
        for (int x = 0; x < t; x++) {
            Model model = models.get(x);
            boolean iscreate = false;
            if (model.options.equals("true")) {
                iscreate = true;
            }
            Object[] obj = {model.table, model.name, model.description, iscreate};
            tbm.addRow(obj);
        }



        Action action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                TableCellListener tcl = (TableCellListener) e.getSource();
                int t = models.size();
                for (int x = 0; x < t; x++) {
                    Model model = models.get(x);
                    if (model.table.equals(tblTable.getValueAt(tcl.getRow(), 0).toString())) {

                        if (tcl.getColumn() == 2) {//description
                            model.description = tcl.getNewValue().toString();
                        }
                        if (tcl.getColumn() == 3) {//create
                            model.options = tcl.getNewValue().toString();
                        }
                    }
                }

            }
        };
        TableCellListener tcl = new TableCellListener(tblTable, action);

        Action action2 = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                TableCellListener tcl = (TableCellListener) e.getSource();
                int t = models.size();
                for (int x = 0; x < t; x++) {
                    Model model = models.get(x);
                    if (model.table.equals(tblTable.getValueAt(postable, 0).toString())) {
                        if (tcl.getColumn() == 5) {//description
                            List<Attribute> attrs = model.attributes;
                            int ta = attrs.size();
                            for (int y = 0; y < ta; y++) {
                                Attribute attr = attrs.get(y);
                                if (attr.name.equals(tblColumn.getValueAt(tcl.getRow(), 0).toString())) {
                                    //models.get(x).attributes.get(y).description = tcl.getNewValue().toString();
                                    attr.description = tcl.getNewValue().toString();
                                }
                            }
                        }
                    }
                }
            }
        };
        TableCellListener tcl2 = new TableCellListener(tblColumn, action2);

        Action action3 = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                TableCellListener tcl = (TableCellListener) e.getSource();
                int t = models.size();
                for (int x = 0; x < t; x++) {
                    Model model = models.get(x);
                    if (model.table.equals(tblTable.getValueAt(postable, 0).toString())) {
                        List<Reference> references = model.references;
                        int ta = references.size();
                        for (int y = 0; y < ta; y++) {
                            Reference reference = references.get(y);
                            if (reference.foreign_key.equals(tblKey.getValueAt(tcl.getRow(), 1).toString())
                                    && reference.model_reference.equals(tblKey.getValueAt(tcl.getRow(), 2).toString())
                                    && reference.attribute_reference.equals(tblKey.getValueAt(tcl.getRow(), 3).toString())) {
                                if (tcl.getColumn() == 0) {//description
                                    reference.name_key = tcl.getNewValue().toString();
                                }
                                if (tcl.getColumn() == 4) {//description
                                    reference.field_reference = tcl.getNewValue().toString();
                                }
                                if (tcl.getColumn() == 5) {//description
                                    reference.description = tcl.getNewValue().toString();
                                }
                            }
                        }
                    }
                }

            }
        };
        TableCellListener tcl3 = new TableCellListener(tblKey, action3);

        tblTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent e) {
                int row = tblTable.rowAtPoint(e.getPoint());
                postable = row;
                //int col = tblTable.columnAtPoint(e.getPoint());
                //JOptionPane.showMessageDialog(null," Value in the cell clicked:" + tblTable.getValueAt(row, 0).toString());

                int t = models.size();
                for (int x = 0; x < t; x++) {
                    Model model = models.get(x);
                    if (model.table.equals(tblTable.getValueAt(row, 0).toString())) {
                        while (tbm_column.getRowCount() > 0) {
                            tbm_column.removeRow(0);
                        }
                        List<Attribute> attrs = model.attributes;
                        int ta = attrs.size();

                        for (int y = 0; y < ta; y++) {
                            Attribute attr = attrs.get(y);
                            boolean notnull = false;
                            if (attr.nullable.equals("1")) {
                                notnull = true;
                            }
                            Object[] obj = {
                                attr.name,
                                attr.type,
                                attr.length,
                                notnull,
                                attr.description
                            };

                            tbm_column.addRow(obj);
                        }
                        while (tbm_keys.getRowCount() > 0) {
                            tbm_keys.removeRow(0);
                        }
                        List<Reference> references = model.references;
                        int tr = references.size();


                        for (int y = 0; y < tr; y++) {
                            Reference reference = references.get(y);
                            Object[] obj = {
                                reference.name_key,
                                reference.foreign_key,
                                reference.model_reference,
                                reference.attribute_reference,
                                reference.field_reference,
                                reference.description
                            };
                            tbm_keys.addRow(obj);
                        }
                    }
                }
            }
        });

        tblKey.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent e) {
                int row = tblKey.rowAtPoint(e.getPoint());
                int col = tblKey.columnAtPoint(e.getPoint());
                if (col == 4) {
                    String m = tblKey.getValueAt(row, 2).toString();
                    int t = models.size();
                    for (int x = 0; x < t; x++) {
                        Model model = models.get(x);
                        if (model.table.equals(m)) {
                            comboBox.removeAllItems();
                            List<Attribute> attrs = model.attributes;
                            int ta = attrs.size();
                            for (int y = 0; y < ta; y++) {
                                Attribute attr = attrs.get(y);
                                comboBox.addItem(attr.name);
                            }
                        }
                    }



                    DefaultCellEditor defaultCellEditor = new DefaultCellEditor(comboBox);
                    tblKey.getColumnModel().getColumn(4).setCellEditor(defaultCellEditor);
                }

            }
        });

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCancel = new javax.swing.JButton();
        btnGenerateModel = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblTable = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblColumn = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblKey = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnGenerateModel.setText("Generar Modelos");
        btnGenerateModel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerateModelActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Tables"));

        jScrollPane1.setViewportView(tblTable);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 744, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Attributes"));

        jScrollPane2.setViewportView(tblColumn);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("References"));

        jScrollPane3.setViewportView(tblKey);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGenerateModel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGenerateModel)
                    .addComponent(btnCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGenerateModelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateModelActionPerformed
        status = true;
        this.setVisible(false);
    }//GEN-LAST:event_btnGenerateModelActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    public boolean isStatus() {
        return status;
    }

    public List<Model> getModels() {
        return this.models;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnGenerateModel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable tblColumn;
    private javax.swing.JTable tblKey;
    private javax.swing.JTable tblTable;
    // End of variables declaration//GEN-END:variables
}
